package com.jpcc.vw.onlineRadio.fragment;

import android.Manifest;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Popup;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatSeekBar;
import android.text.Html;
import android.text.TextUtils;
import android.text.format.DateUtils;
/*Start by menglingqiang*/
import android.util.Log;
/*End by menglingqiang*/
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jpcc.vw.callback.NewPayResultListener;
import com.jpcc.vw.mylibrary.PaySdk;
import com.jpcc.vw.onlineRadio.R;
import com.jpcc.vw.onlineRadio.activity.AlbumDetailActivity;
import com.jpcc.vw.onlineRadio.activity.AlbumProgramsActivity;
/*Start by menglingqiang*/
import com.jpcc.vw.onlineRadio.activity.MainActivity;
import com.jpcc.vw.onlineRadio.activity.TopListRanksActivity;
/*End by menglingqiang*/
import com.jpcc.vw.onlineRadio.adapter.RadioScheduleAdapter;
import com.jpcc.vw.onlineRadio.application.MusicApplication;
import com.jpcc.vw.onlineRadio.constants.Constants;
import com.jpcc.vw.onlineRadio.db.DatabaseHelperOrm;
import com.jpcc.vw.onlineRadio.db.DownloadTrackDbBean;
import com.jpcc.vw.onlineRadio.db.FavouriteAlbumDbBean;
import com.jpcc.vw.onlineRadio.http.HttpClient;
import com.jpcc.vw.onlineRadio.model.IRadio;
import com.jpcc.vw.onlineRadio.model.action.MessageAction;
import com.jpcc.vw.onlineRadio.model.action.OnlineRadioItemSelectedAction;
import com.jpcc.vw.onlineRadio.model.action.RefreshFavStatusAction;
import com.jpcc.vw.onlineRadio.model.action.ShowHideUnavailableAction;
import com.jpcc.vw.onlineRadio.model.bean.AddAlbumCollectionBean;
import com.jpcc.vw.onlineRadio.model.bean.AddAlbumCollectionEntity;
import com.jpcc.vw.onlineRadio.model.bean.AddCancelAlbumBean;
import com.jpcc.vw.onlineRadio.model.bean.BaseBean;
import com.jpcc.vw.onlineRadio.model.bean.CPInfoBean;
import com.jpcc.vw.onlineRadio.model.bean.PlaceOrderBean;
import com.jpcc.vw.onlineRadio.model.bean.PlayInfoBean;
import com.jpcc.vw.onlineRadio.model.bean.PriceTypeInfoBean;
import com.jpcc.vw.onlineRadio.model.bean.RadioDeailBean;
import com.jpcc.vw.onlineRadio.model.bean.RecentAlbumRadioTrackBean;
import com.jpcc.vw.onlineRadio.model.bean.Track;
import com.jpcc.vw.onlineRadio.model.bean.VIPInfoBean;
import com.jpcc.vw.onlineRadio.model.bean.XiMaLaYaOrderBean;
import com.jpcc.vw.onlineRadio.model.impl.RadioImpl;
import com.jpcc.vw.onlineRadio.service.AlbumRadioAudioPlayer;
import com.jpcc.vw.onlineRadio.service.OnAlbumRadioPlayerEventListener;
import com.jpcc.vw.onlineRadio.utils.CommonSubscriber;
import com.jpcc.vw.onlineRadio.utils.ConfigReaderUtils;
import com.jpcc.vw.onlineRadio.utils.PermissionReq;
import com.jpcc.vw.onlineRadio.utils.PreferenceUtils;
import com.jpcc.vw.onlineRadio.utils.ProcessInfoUtils;
import com.jpcc.vw.onlineRadio.utils.SyncFavUtils;
import com.jpcc.vw.onlineRadio.utils.ToastUtils;
import com.jpcc.vw.onlineRadio.utils.TrackUtils;
import com.jpcc.vw.onlineRadio.utils.TransformUtils;
import com.jpcc.vw.onlineRadio.widget.ScrollTextView;
/*Start by menglingqiang*/
import com.jpcc.vw.tracelog.TracelogInterface;
/*End by menglingqiang*/
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadLargeFileListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.lzy.okhttpserver.download.DownloadInfo;
import com.lzy.okhttpserver.download.DownloadManager;
import com.lzy.okhttpserver.download.DownloadService;
import com.lzy.okhttpserver.listener.DownloadListener;
import com.orhanobut.logger.Logger;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.sql.SQLException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTouch;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import rx.functions.Action0;

/**
 * 播放器画面
 */
public class PlayerFragment extends com.jpcc.vw.onlineRadio.base.BaseFragment implements OnAlbumRadioPlayerEventListener, SeekBar.OnSeekBarChangeListener {

    @BindView(R.id.imv_more)
    ImageView imv_more;
    @BindView(R.id.tv_album_name)
    TextView tv_album_name;
    @BindView(R.id.tv_program_name)
    TextView tv_program_name;
    @BindView(R.id.imv_cover_art)
    ImageView imv_cover_art;
    @BindView(R.id.sb_progress)
    AppCompatSeekBar sb_progress;
    @BindView(R.id.tv_mianing_time)
    TextView tv_mianing_time;
    @BindView(R.id.imv_previous)
    ImageView imv_previous;
    @BindView(R.id.imv_play_next)
    ImageView imv_play_next;
    @BindView(R.id.imv_play_status)
    ImageView imv_play_status;
    @BindView(R.id.imv_download)
    ImageView imv_download;
    @BindView(R.id.imv_favourite)
    ImageView imv_favourite;
    @BindView(R.id.layout_player)
    RelativeLayout layout_player;
    @BindView(R.id.layout_not_available)
    RelativeLayout layout_not_available;
    @BindView(R.id.tv_hint)
    TextView tv_hint;
    @BindView(R.id.imv_cp_logo)
    ImageView imv_cp_logo;
    @BindView(R.id.layout_play_status)
    RelativeLayout layout_play_status;
    @BindView(R.id.layout_previous)
    RelativeLayout layout_previous;
    @BindView(R.id.layout_play_next)
    RelativeLayout layout_play_next;
    @BindView(R.id.imv_vip_status)
    ImageView imv_vip_status;
    @BindView(R.id.imv_covert)
    ImageView imv_covert;
    @BindView(R.id.layout_more)
    RelativeLayout layout_more;
    @BindView(R.id.imv_cover_middle)
    ImageView imv_cover_middle;
    @BindView(R.id.imv_cover_small)
    ImageView imv_cover_small;
    private DownloadManager downloadManager;

    private PopupWindow mPopWindow;

    private int mLastProgress;
    private IRadio model;

    private RecentAlbumRadioTrackBean recent;

    private boolean isDraggingProgress;

    private IRadio radioModel;

    private RadioScheduleAdapter adapter;
    private List<RadioDeailBean.RadioSchedule> datas = new ArrayList<>();
    MaterialDialog dialog;
    private boolean isAccountRight = true;
    private int localPercent = 0;
    private MaterialDialog storageDialog;
    private MaterialDialog exceedFavNumDialog;
    private DatabaseHelperOrm helper;
//    private AlbumDetailAdapter adapter;
//    private List<Track> datas = new ArrayList<>();
//    private int page_index_album=1;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_player;
    }


    private void setSeekbarEnable(boolean enable) {
        if (sb_progress != null) {
            if (!enable) {
                sb_progress.setClickable(false);
                sb_progress.setEnabled(false);
                sb_progress.setSelected(false);
                sb_progress.setFocusable(false);
            } else {
                sb_progress.setClickable(true);
                sb_progress.setEnabled(true);
                sb_progress.setSelected(true);
                sb_progress.setFocusable(true);
                sb_progress.setOnSeekBarChangeListener(this);
            }
        }
    }


    @Override
    public void setupView() {
//        action=new MessageAction();
//        action.setAccountRight(false);
//        action.setTips("abc");
        if (!Constants.isRelease) {
            action = new MessageAction();
            action.setAccountRight(true);
        }
        ButterKnife.bind(this, mContextView);
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        EventBus.getDefault().register(this);
        radioModel = new RadioImpl();
        if (AlbumRadioAudioPlayer.get().isPlaying()) {
//            imv_play_status.setImageResource(R.drawable.to_pause);
            imv_play_status.setBackgroundResource(R.drawable.bg_status_pause);
        } else {
//            imv_play_status.setImageResource(R.drawable.to_play);
            imv_play_status.setBackgroundResource(R.drawable.bg_status_play);
        }
        storageDialog = new MaterialDialog.Builder(getActivity()).title(getResources().getString(R.string.string_30)).content(getResources().getString(R.string.string_108)).negativeText(getResources().getString(R.string.string_32)).build();
        exceedFavNumDialog = new MaterialDialog.Builder(getActivity()).title(getResources().getString(R.string.string_30)).content(getResources().getString(R.string.string_112)).negativeText(getResources().getString(R.string.string_32)).build();


        String str3 = "<font color='#f0f2f7'>" + formatTime("mm:ss", 0) + "</font><font color='#b3b6be'>" + "/" + formatTime("mm:ss", 0) + "</font>";
//        tv_mianing_time.setText(Html.fromHtml(str3));
//        imv_play_status.setEnabled(false);
//        layout_play_status.setEnabled(false);
    }

    @Override
    public void setupData() {
        getCpInfo();
        getVipInfo();
//        SyncFavUtils.syncFav(getContext(), new SyncFavUtils.onSyncFav() {
//            @Override
//            public void onSyncFavSuccess() {
//                favStatus();
//            }
//
//            @Override
//            public void onsyncFavFail() {
//
//            }
//        });
        favStatus();
    }

    private void getCpInfo() {
        if (model == null) {
            model = new RadioImpl();
        }

        /*Start by menglingqiang*/
        Date dt = new Date();
        try {
            TracelogInterface inter = MusicApplication.getLogInterface();
            if (inter != null) {
                inter.sendLogData(dt.toString(), dt.toString(), PlayerFragment.this.getClass().getName(), "DEBUG", "400", "GetCPInfo Request");
            } else {
                Log.e("JPCC", "inter == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*End by menglingqiang*/

        model.GetCPInfo().subscribe(new CommonSubscriber<CPInfoBean>() {
            @Override
            public void onSuccess(CPInfoBean response) {
                if (response != null && response.getData() != null) {
//                    Glide.with(getContext())
//                            .load(response.getData().getLogo())
//                            .into(imv_cp_logo);
                }
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), PlayerFragment.this.getClass().getName(), "DEBUG", "400", "GetCPInfo onSuccess");
                    } else {
                        Log.e("JPCC", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }

            @Override
            public void onFailure(BaseBean response) {
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), PlayerFragment.this.getClass().getName(), "ERROR", "400", "GetCPInfo onFailure");
                    } else {
                        Log.e("jgj", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }
        });
    }

    public void getVipInfo() {
//        if(model==null){
//            model=new RadioImpl();
//        }
        if (radioModel == null) {
            radioModel = new RadioImpl();
        }
        radioModel.QueryVIPInfo().subscribe(new CommonSubscriber<VIPInfoBean>() {
            @Override
            public void onSuccess(VIPInfoBean response) {
                if (response.getData() != null && response.getData().isVipFlag()) {
                    imv_vip_status.setImageResource(R.drawable.vip);
                } else {
                    imv_vip_status.setImageResource(R.drawable.unvip);
                }
            }

            @Override
            public void onFailure(BaseBean response) {
//                imv_vip_status.setImageResource(R.drawable.unvip);
            }
        });
    }


    @Override
    public void onStart() {
        super.onStart();
        sb_progress.setOnSeekBarChangeListener(this);
        layout_previous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isAccountRight) {
                    return;
                }
                Constants.LastModeFlag = false;
                AlbumRadioAudioPlayer.get().prev();
            }
        });

        layout_play_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                sb_progress.setProgress(0);
                if (!isAccountRight) {
                    return;
                }
//                Constants.LastModeFlag = false;
//                AlbumRadioAudioPlayer.get().next();
//                if(AlbumRadioAudioPlayer.get().getPlayMusic()!=null&&AlbumRadioAudioPlayer.get().getPlayMusic().isLive()){
//                    ToastUtils.show(R.string.string_109);
//                }
            }
        });
        layout_play_status.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isAccountRight) {
                    return;
                }
                Logger.i("radio start fragment");
                Constants.LastModeFlag = false;


                if (AlbumRadioAudioPlayer.get().isPlaying()) {
                    Constants.FLAG_PAUSE_MANUAL = true;
                    Constants.FLAG_FOCUS_ON_SELF = false;
                }
                if (AlbumRadioAudioPlayer.get().isPausing()) {
                    Constants.FLAG_PAUSE_MANUAL = false;
                    Constants.FLAG_FOCUS_ON_SELF = true;
                }

                AlbumRadioAudioPlayer.get().playPauseAbandonFocus();

            }
        });
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        String currentLanguage = newConfig.locale.getLanguage();
        if (AlbumRadioAudioPlayer.get().getPlayMusic() != null) {
            tv_program_name.setText(AlbumRadioAudioPlayer.get().getPlayMusic().getTrackName());
            tv_album_name.setText(AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumName());
        } else {
            tv_album_name.setVisibility(View.INVISIBLE);
            if ("zh".equals(currentLanguage)) {
                tv_program_name.setText("请到\"发现\"查找节目");
                tv_album_name.setText("请到\"发现\"查找节目");
            } else {
                tv_program_name.setText("Please find program in \"Discover\"");
                tv_album_name.setText("Please find program in \"Discover\"");
            }
        }
    }

    @Override
    public void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        pressHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

    boolean isLongPress = false;

    Handler pressHandler = new Handler();
    /**
     * 长按快退
     */
    Runnable pLongPress = new Runnable() {
        @Override
        public void run() {
            isLongPress = true;
            duration = duration - 1000;
            if (pressMilliSeconds > 0 && pressMilliSeconds < 4000) {
                delay = 250;
            } else if (pressMilliSeconds > 4000 && pressMilliSeconds < 8000) {
                delay = 125;
            } else if (pressMilliSeconds > 8000 && pressMilliSeconds < 12000) {
                delay = 50;
            } else if (pressMilliSeconds > 12000) {
                delay = 25;
            }

            AlbumRadioAudioPlayer.get().setUnmute();
            if (duration <= 0) {
                delay = 0;
                pressMilliSeconds = 0;
                delay = 0;
                duration = 0;
                AlbumRadioAudioPlayer.get().setOnpublishFlag(true);
                AlbumRadioAudioPlayer.get().seekTo(0);
                pressHandler.removeCallbacks(pLongPress);
                pressMilliSeconds = pressMilliSeconds + delay;
            } else {
                AlbumRadioAudioPlayer.get().setOnpublishFlag(false);
                if (duration < 0) {
                    duration = 0;
                }
                sb_progress.setProgress(duration);
                String str3 = "<font color='#f0f2f7'>" + formatTime("mm:ss", duration) + "</font><font color='#b3b6be'>" + "/" + formatTime("mm:ss", AlbumRadioAudioPlayer.get().getPlayMusic().getDuration()) + "</font>";
                tv_mianing_time.setText(Html.fromHtml(str3));
                pressMilliSeconds = pressMilliSeconds + delay;
                pressHandler.postDelayed(pLongPress, delay);
            }
        }
    };

    /**
     * 长按快进
     */
    private int pressMilliSeconds = 0;
    private int delay = 0;
    private int duration = 0;
    Runnable nLongPress = new Runnable() {
        @Override
        public void run() {
            isLongPress = true;
//            long duration = AlbumRadioAudioPlayer.get().getPlayMusic().getDuration();
//            long seek = position + 2000;
//            if (seek > duration) {
//                seek = duration;
//            }
//            pressMilliSeconds=500+pressMilliSeconds;
//            if(pressMilliSeconds==1000){
//                AlbumRadioAudioPlayer.get().setMate(4);
//            }
//            else if(pressMilliSeconds==4000){
//                AlbumRadioAudioPlayer.get().setMate(8);
//            }
//            else if(pressMilliSeconds==8000){
//                AlbumRadioAudioPlayer.get().setMate(16);
//            }
//            else if(pressMilliSeconds==12000){
//                AlbumRadioAudioPlayer.get().setMate(32);
//            }

            AlbumRadioAudioPlayer.get().setUnmute();
            AlbumRadioAudioPlayer.get().setOnpublishFlag(false);

            if (pressMilliSeconds > 0 && pressMilliSeconds < 4000) {
                delay = 250;
            } else if (pressMilliSeconds > 4000 && pressMilliSeconds < 8000) {
                delay = 125;
            } else if (pressMilliSeconds > 8000 && pressMilliSeconds < 12000) {
                delay = 50;
            } else if (pressMilliSeconds > 12000) {
                delay = 25;
            }

            duration = duration + 1000;
            if (duration == AlbumRadioAudioPlayer.get().getPlayMusic().getDuration() || duration > AlbumRadioAudioPlayer.get().getPlayMusic().getDuration()) {
                AlbumRadioAudioPlayer.get().next();
            } else {
                sb_progress.setProgress(duration);
                String str3 = "<font color='#f0f2f7'>" + formatTime("mm:ss", duration) + "</font><font color='#b3b6be'>" + "/" + formatTime("mm:ss", AlbumRadioAudioPlayer.get().getPlayMusic().getDuration()) + "</font>";
                tv_mianing_time.setText(Html.fromHtml(str3));
            }

            pressMilliSeconds = pressMilliSeconds + delay;
            pressHandler.postDelayed(nLongPress, delay);
        }
    };

    @OnTouch({R.id.layout_previous, R.id.layout_play_next})
    public boolean onTouch(View v, MotionEvent event) {
        switch (v.getId()) {
            case R.id.imv_previous:
            case R.id.layout_previous:
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        if (isAccountRight) {
                            isLongPress = false;
                            pressMilliSeconds = 1;
                            pressHandler.removeCallbacks(nLongPress);
                            pressHandler.postDelayed(pLongPress, 500);
                            imv_previous.setPressed(true);
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        if (isAccountRight) {
                            Constants.FLAG_PAUSE_MANUAL = false;
                            pressHandler.removeCallbacks(pLongPress);
                            imv_previous.setPressed(false);
                            if (isLongPress) {
                                if (AlbumRadioAudioPlayer.get().getPlayMusic() != null && !AlbumRadioAudioPlayer.get().getPlayMusic().isLive()) {
                                    AlbumRadioAudioPlayer.get().setOnpublishFlag(true);
                                    AlbumRadioAudioPlayer.get().seekTo(duration);
                                    pressMilliSeconds = 0;
                                    delay = 0;
                                    duration = 0;
                                }
                            }
                            if (!isLongPress) {
                                AlbumRadioAudioPlayer.get().prev();
                            }
                        }
                        break;
                }
                break;
            case R.id.layout_play_next:
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        if (isAccountRight) {
                            isLongPress = false;
                            layout_play_next.setSelected(true);
                            imv_play_next.setPressed(true);
                            pressHandler.removeCallbacks(pLongPress);
                            pressMilliSeconds = 1;
                            pressHandler.postDelayed(nLongPress, 500);
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        if (isAccountRight) {
                            Constants.FLAG_PAUSE_MANUAL = false;
                            pressHandler.removeCallbacks(nLongPress);


//                            AlbumRadioAudioPlayer.get().setMate(1);
                            layout_play_next.setSelected(false);
                            imv_play_next.setPressed(false);

                            if (isLongPress) {
                                if (AlbumRadioAudioPlayer.get().getPlayMusic() != null && !AlbumRadioAudioPlayer.get().getPlayMusic().isLive()) {
                                    AlbumRadioAudioPlayer.get().setOnpublishFlag(true);
                                    AlbumRadioAudioPlayer.get().seekTo(duration);
                                    pressMilliSeconds = 0;
                                    delay = 0;
                                    duration = 0;
                                }
                            }


                            if (!isLongPress) {
                                if (AlbumRadioAudioPlayer.get().getPlayMusic() != null && AlbumRadioAudioPlayer.get().getPlayMusic().isLive()) {
                                    ToastUtils.show(R.string.string_109);
                                }

                                AlbumRadioAudioPlayer.get().next();
                            }
                        }
                        break;

                }
                break;
        }
        return true;
    }


    @OnClick({R.id.layout_more, R.id.imv_download})
    void doClicks(View view) {
        if (!isAccountRight) {
            return;
        }
        int id = view.getId();
        switch (id) {
            case R.id.layout_more:
                RecentAlbumRadioTrackBean current = AlbumRadioAudioPlayer.get().getPlayMusic();
                if (current != null && "radio".equals(current.getType())) {
                    Intent intent_more = new Intent(getActivity(), AlbumProgramsActivity.class);
                    intent_more.putExtra("key_radio_id", current.getAlbumId());
                    intent_more.putExtra("key_radio_name", current.getAlbumName());
                    startActivity(intent_more);
                } else if (current != null && "album".equals(current.getType())) {
                    Intent intent_more = new Intent(getActivity(), AlbumDetailActivity.class);
                    intent_more.putExtra("key_album_id", current.getAlbumId());
                    intent_more.putExtra("key_is_radio", false);
                    intent_more.putExtra("key_from", current.getFrom());
                    intent_more.putExtra("isvipFree", current.isVipFree());
                    startActivity(intent_more);
                }
                break;
            case R.id.imv_download:
                if (AlbumRadioAudioPlayer.get().getPlayMusic() == null) {
                    return;
                }
                if (action != null && action.isAccountRight()) {

                    File downloadDir = new File(TrackUtils.getTrackDir());
//                    Logger.i((getFolderSize(downloadDir) / 1024 / 1024 / 1024 / 1024) + "");
                    if (getFolderSize(downloadDir) >= (2L * 1024 * 1024 * 1024 * 1024)) {
//                        if (storageDialog != null && !storageDialog.isShowing()) {
//                            storageDialog.show();
//                        }
                        NotificationManager notificationManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
                        Intent setAlertIntent = new Intent("com.jpcc.vw.PlayerFragment");
                        PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, setAlertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                        Popup popup = new Popup(getResources().getString(R.string.string_30), getResources().getString(R.string.string_108));
                        popup.setActionOne(getResources().getString(R.string.string_32), pendingIntent);
                        popup.setActionCancel(getResources().getString(R.string.string_33), "cancel");
                        notificationManager.addPopup(0x0008, popup);

                        return;
                    }

                    downloadTrack2();
                }
                break;
        }
    }


    public static long getFolderSize(java.io.File file) {
        long size = 0;
        java.io.File[] fileList = file.listFiles();
        if (fileList == null) {
            return 0;
        }
        for (int i = 0; i < fileList.length; i++) {

            if (fileList[i].isDirectory()) {
                size = size + getFolderSize(fileList[i]);

            } else {
                size = size + fileList[i].length();

            }
        }

        return size;
    }


    private void showPopwindow(boolean isRadio) {
        View contentView = LayoutInflater.from(getContext()).inflate(R.layout.pop_program_album_radio, null);
        mPopWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        mPopWindow.setContentView(contentView);
        mPopWindow.setOutsideTouchable(true);
        mPopWindow.setTouchable(true);
        mPopWindow.setBackgroundDrawable(new BitmapDrawable());
        //设置各个控件的点击响应
        //显示PopupWindow
        View rootview = LayoutInflater.from(getContext()).inflate(R.layout.fragment_player, null);

        if (isRadio) {
//            BrowseLocalRadios();
//            SmartRefreshLayout swipe_refrsh_online_radio=(SmartRefreshLayout)contentView.findViewById(R.id.swipe_refrsh_tracks);
            datas = new ArrayList<>();
            adapter = new RadioScheduleAdapter(datas, getContext());
            ListView recyclerview_online_radio = (ListView) contentView.findViewById(R.id.recyclerview_tracks);
//            LinearLayoutManager manager = new LinearLayoutManager(getContext());
//            manager.setItemPrefetchEnabled(false);
//            recyclerview_online_radio.setLayoutManager(manager);
            recyclerview_online_radio.setAdapter(adapter);
            mPopWindow.showAtLocation(rootview, Gravity.RIGHT, 0, 0);
            Date today = new Date();
            Calendar c = Calendar.getInstance();
            c.setTime(today);
            int weekday = c.get(Calendar.DAY_OF_WEEK);
            radioModel.getLiveSchedules(AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId(), weekday - 1).doOnSubscribe(new Action0() {
                @Override
                public void call() {
                    showProgress();
                }
            }).subscribe(new CommonSubscriber<RadioDeailBean>() {
                @Override
                public void onSuccess(RadioDeailBean response) {
                    hideProgress();
                    if (response.getData() != null) {
                        datas.clear();
                        datas.addAll(response.getData());
                        adapter.setDatas(datas);
                    }
                }

                @Override
                public void onFailure(BaseBean response) {
                    hideProgress();
                    ToastUtils.show(response.getStatusMessage());
                }
            });

        } else {
//            SmartRefreshLayout swipe_refrsh_online_radio=(SmartRefreshLayout)contentView.findViewById(R.id.swipe_refrsh_tracks);
//            localRaiods = new ArrayList<>();
//            localRadioAdapter = new LocalOnlineRadioInfoAdapter(getContext(), localRaiods);
//            RecyclerView recyclerview_online_radio=(RecyclerView)contentView.findViewById(R.id.recyclerview_tracks);
//            LinearLayoutManager manager = new LinearLayoutManager(getContext());
//            manager.setItemPrefetchEnabled(false);
//            recyclerview_online_radio.setLayoutManager(manager);
//            recyclerview_online_radio.setAdapter(localRadioAdapter);
//            mPopWindow.showAtLocation(rootview, Gravity.RIGHT, 0, 0);
//            int local_page = page_index_album;
//            if (is_refresh) {
//                local_page = 1;
//            }
//            radioModel.GetAlbumBrowse(albumId, local_page).doOnSubscribe(new Action0() {
//                @Override
//                public void call() {
//                    showProgress();
//                }
//            }).subscribe(new CommonSubscriber<AlbumBrowseBean>() {
//                @Override
//                public void onSuccess(AlbumBrowseBean response) {
//                    hideProgress();
//                    swipe_refrsh_online_radio.finishRefresh();
//                    swipe_refrsh_online_radio.finishLoadmore();
//                    if ((response.getData().getTracks() != null) && (response.getData().getTracks().size() > 0)) {
//                        if (is_refresh) {
//                            datas.clear();
//                            page_index = 1;
//                        }
//                        datas.addAll(response.getData().getTracks());
//                        for (Track track : datas) {
//                            track.setTrackIntro(response.getData().getAlbumIntro());
//                        }
//                        adapter.setData(datas);
//                        adapter.notifyDataSetChanged();
//                        page_index++;
//                    } else {
//                        swipe_refrsh_tracks.finishLoadmore();
//                        swipe_refrsh_tracks.setEnableLoadmore(false);
//                    }
//                }
//
//                @Override
//                public void onFailure(BaseBean response) {
//                    hideProgress();
//                    ToastUtils.show(response.getStatusMessage());
//                    swipe_refrsh_tracks.finishRefresh();
//                }
//            });
        }
    }


//    private QuietDownloader mDownloader = QuietDownloader.getImpl();
//    private final DataUpdatedWatcher mDataUpdatedWatcher = new DataUpdatedWatcher() {
//        @Override
//        public void notifyUpdate(DownloadEntry data) {
//            if (data != null && AlbumRadioAudioPlayer.get().getPlayMusic() != null) {
//                Logger.i("notifyUpdate-->" + new Gson().toJson(data));
//                if (data.name.equals(AlbumRadioAudioPlayer.get().getPlayMusic().getTrackName())) {
//                    Logger.i("notifyUpdate-->" + data.status);
//                }
//            }
//        }
//    };

//    private void doDownloadTracks3() {
//        RecentAlbumRadioTrackBean result = AlbumRadioAudioPlayer.get().getPlayMusic();
//        if (result == null) {
//            return;
//        }
//        if (result.canDownLoad) {
//            if (TextUtils.isEmpty(result.getDownloadUrl())) {
//                ToastUtils.show(R.string.string_50);
//                return;
//            }
//            try {
//                DownloadTrackDbBean resultQuery = DatabaseHelperOrm.getHelper(getContext()).getDownloadDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("albumId", result.getAlbumId()).and().eq("trackId", result.getTrackId()).queryForFirst();
//                if (resultQuery != null) {
//                    ToastUtils.show(R.string.string_29);
//                    resultQuery.setTimeStamp(new Date().getTime());
//                    DatabaseHelperOrm.getHelper(getContext()).getDownloadDao().update(resultQuery);
//                } else {
//                    final String[] path = {TrackUtils.getTrackDir() + result.getAlbumId() + result.getTrackId() + "." + result.getDownloadUrl().substring(result.getDownloadUrl().length() - 3)};
//                    File file = new File(path[0]);
//                    PermissionReq.with(this).permissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).result(new PermissionReq.Result() {
//                        @Override
//                        public void onGranted() {
//                            DownloadEntry mDownloadEntry = new DownloadEntry(result.getDownloadUrl(), result.getAlbumId() + result.getTrackId() + "." + result.getDownloadUrl().substring(result.getDownloadUrl().length() - 3));
//                            mDownloader.download(mDownloadEntry);
//                            mDownloader.removeObserver(mDataUpdatedWatcher);
//                            mDownloader.addObserver(mDataUpdatedWatcher);
//                        }
//
//                        @Override
//                        public void onDenied() {
//                            ToastUtils.show(R.string.string_41);
//                        }
//                    }).request();
//                }
//            } catch (SQLException e) {
//                e.printStackTrace();
//            }
//        }
//    }


    private void downloadTrack2() {
        RecentAlbumRadioTrackBean result = AlbumRadioAudioPlayer.get().getPlayMusic();
        if (result == null) {
            return;
        }
        DownloadTrackDbBean searchResult = null;

        try {
            searchResult = helper.getDownloadDao().queryBuilder().where().eq("albumId", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId()).and().eq("userId", MusicApplication.GetUserId()).and().eq("trackId", AlbumRadioAudioPlayer.get().getPlayMusic().getTrackId()).queryForFirst();
        } catch (SQLException e) {
            e.printStackTrace();
        }


        if (true) {
            if (TextUtils.isEmpty(result.getDownloadUrl())) {
                if (searchResult != null) {
//                    ToastUtils.show(R.string.string_114);
                } else {
//                    ToastUtils.show(R.string.string_95);
                }
                return;
            }
            try {
                DownloadTrackDbBean resultQuery = DatabaseHelperOrm.getHelper(getContext()).getDownloadDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("albumId", result.getAlbumId()).and().eq("trackId", result.getTrackId()).queryForFirst();
                if (resultQuery != null) {
//                    ToastUtils.show(R.string.string_114);
                    resultQuery.setTimeStamp(new Date().getTime());
                    DatabaseHelperOrm.getHelper(getContext()).getDownloadDao().update(resultQuery);
                } else {
                    final String[] path = {TrackUtils.getTrackDir() + result.getAlbumId() + result.getTrackId() + "." + result.getDownloadUrl().substring(result.getDownloadUrl().length() - 3)};
                    File file = new File(path[0]);
//                    ToastUtils.show(R.string.string_49);
                    boolean showMiddle = true;
                    FileDownloader.setup(getContext());

                    PermissionReq.with(this).permissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).result(new PermissionReq.Result() {
                        @Override
                        public void onGranted() {
                            if (downloadManager == null) {
                                downloadManager = DownloadManager.getInstance(getActivity());
                            }
                            downloadManager.addTaskWithName(result.getDownloadUrl(), new DownloadListener() {
                                @Override
                                public void onProgress(DownloadInfo downloadInfo) {
                                    //adapter.notifyDataSetChanged();
                                }

                                @Override
                                public void onFinish(DownloadInfo downloadInfo) {
                                    DownloadTrackDbBean info = new DownloadTrackDbBean();
                                    info.setUserId(MusicApplication.GetUserId());
                                    info.setAlbumId(result.getAlbumId());
                                    info.setCover(result.getCover());
                                    info.setAlbumName(result.getAlbumName());
                                    info.setAuthor(result.getAuthor());
                                    info.setTrackId(result.getTrackId());
                                    info.setTrackName(result.getTrackName());
                                    info.setTrackUrl(file.getAbsolutePath());//TrackUtils.getTrackDir() + result.getAlbumId() + result.getTrackId() + "." + result.getDownloadUrl().substring(result.getDownloadUrl().length() - 3, result.getDownloadUrl().length()));
                                    info.setTimeStamp(new Date().getTime());
                                    info.setDuration(result.getDuration());
                                    info.setAlbumIntro("");
                                    try {
                                        DownloadTrackDbBean resultQuery = DatabaseHelperOrm.getHelper(getContext()).getDownloadDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("albumId", info.getAlbumId()).and().eq("trackId", info.getTrackId()).queryForFirst();
                                        if (resultQuery != null) {
                                            resultQuery.setTimeStamp(new Date().getTime());
                                            DatabaseHelperOrm.getHelper(getContext()).getDownloadDao().update(resultQuery);
                                        } else {
                                            DatabaseHelperOrm.getHelper(getContext()).getDownloadDao().create(info);
                                        }
                                        ToastUtils.show(getContext().getString(R.string.string_28));
                                    } catch (SQLException e) {
//                                        ToastUtils.show(getContext().getString(R.string.string_111));
                                        e.printStackTrace();
                                    }
                                    imv_download.setImageResource(R.drawable.downloadeded);
                                    imv_download.setEnabled(true);
                                }

                                @Override
                                public void onError(DownloadInfo downloadInfo, String errorMsg, Exception e) {
                                    ToastUtils.show(R.string.string_111);
                                    imv_download.setImageResource(R.drawable.un_download);
                                    imv_download.setEnabled(true);
                                    if (downloadManager == null) {
                                        downloadManager = DownloadService.getDownloadManager(getActivity());
                                    }
                                    downloadManager.removeTaskByTrackId(result.getTrackId() + "");
                                }

                                @Override
                                public void onAdd(DownloadInfo downloadInfo) {
                                    super.onAdd(downloadInfo);
                                    ToastUtils.show(R.string.string_49);
                                    doDownloadAnim();
//                                    adapter.notifyDataSetChanged();

                                }
                            }, true, "" + result.getAlbumId() + result.getTrackId() + "." + result.getDownloadUrl().substring(result.getDownloadUrl().length() - 3));


                        }

                        @Override
                        public void onDenied() {
//                            ToastUtils.show(R.string.string_41);
                        }
                    }).request();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {
            ToastUtils.show(R.string.string_95);
        }
    }

    private void downloadTrack() {
        RecentAlbumRadioTrackBean result = AlbumRadioAudioPlayer.get().getPlayMusic();
        if (result == null) {
            return;
        }
        if (result.canDownLoad) {
            if (TextUtils.isEmpty(result.getDownloadUrl())) {
                ToastUtils.show(R.string.string_50);
                return;
            }
            try {
                DownloadTrackDbBean resultQuery = DatabaseHelperOrm.getHelper(getContext()).getDownloadDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("albumId", result.getAlbumId()).and().eq("trackId", result.getTrackId()).queryForFirst();
                if (resultQuery != null) {
                    ToastUtils.show(R.string.string_29);
                    resultQuery.setTimeStamp(new Date().getTime());
                    DatabaseHelperOrm.getHelper(getContext()).getDownloadDao().update(resultQuery);
                } else {
                    final String[] path = {TrackUtils.getTrackDir() + result.getAlbumId() + result.getTrackId() + "." + result.getDownloadUrl().substring(result.getDownloadUrl().length() - 3)};
                    File file = new File(path[0]);
                    ToastUtils.show(R.string.string_49);
                    boolean showMiddle = true;
                    PermissionReq.with(this).permissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE).result(new PermissionReq.Result() {
                        @Override
                        public void onGranted() {
                            OkHttpUtils
                                    .get()
                                    .url(result.getDownloadUrl())
                                    .build().execute(new FileCallBack(TrackUtils.getTrackDir(), "" + result.getAlbumId() + result.getTrackId() + "." + result.getDownloadUrl().substring(result.getDownloadUrl().length() - 3, result.getDownloadUrl().length())) {
                                @Override
                                public void onError(Call call, Exception e, int id) {
                                    ToastUtils.show(getContext().getString(R.string.string_27));
                                }

                                @Override
                                public void onResponse(File response, int id) {
                                    DownloadTrackDbBean info = new DownloadTrackDbBean();
                                    info.setUserId(MusicApplication.GetUserId());
                                    info.setAlbumId(result.getAlbumId());
                                    info.setCover(result.getCover());
                                    info.setAlbumName(result.getAlbumName());
                                    info.setAuthor(result.getAuthor());
                                    info.setTrackId(result.getTrackId());
                                    info.setTrackName(result.getTrackName());
                                    info.setTrackUrl(file.getAbsolutePath());//TrackUtils.getTrackDir() + result.getAlbumId() + result.getTrackId() + "." + result.getDownloadUrl().substring(result.getDownloadUrl().length() - 3, result.getDownloadUrl().length()));
                                    info.setTimeStamp(new Date().getTime());
                                    info.setDuration(result.getDuration());
                                    info.setAlbumIntro("");
                                    try {
                                        DownloadTrackDbBean resultQuery = DatabaseHelperOrm.getHelper(getContext()).getDownloadDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("albumId", info.getAlbumId()).and().eq("trackId", info.getTrackId()).queryForFirst();
                                        if (resultQuery != null) {
                                            resultQuery.setTimeStamp(new Date().getTime());
                                            DatabaseHelperOrm.getHelper(getContext()).getDownloadDao().update(resultQuery);
                                        } else {
                                            DatabaseHelperOrm.getHelper(getContext()).getDownloadDao().create(info);
                                        }
                                        ToastUtils.show(getContext().getString(R.string.string_28));
                                    } catch (SQLException e) {
                                        ToastUtils.show(getContext().getString(R.string.string_27));
                                        e.printStackTrace();
                                    }
                                    imv_download.setImageResource(R.drawable.downloadeded);
                                }

                                @Override
                                public void inProgress(float progress, long total, int id) {
                                }
                            });
                        }

                        @Override
                        public void onDenied() {
                            ToastUtils.show(R.string.string_41);
                        }
                    }).request();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {
            ToastUtils.show(R.string.string_42);
        }
    }

    private AnimationDrawable frameAnim;

    private void doDownloadAnim() {
        if (AlbumRadioAudioPlayer.get().getPlayMusic() != null) {
            final String[] path = {TrackUtils.getTrackDir() + AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId() + AlbumRadioAudioPlayer.get().getPlayMusic().getTrackId() + "." + AlbumRadioAudioPlayer.get().getPlayMusic().getDownloadUrl().substring(AlbumRadioAudioPlayer.get().getPlayMusic().getDownloadUrl().length() - 3)};
            byte fileStatus = FileDownloader.getImpl().getStatus(AlbumRadioAudioPlayer.get().getPlayMusic().getDownloadUrl(), path[0]);
            DownloadTrackDbBean resultQuery = null;
            try {
                resultQuery = DatabaseHelperOrm.getHelper(getContext()).getDownloadDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("albumId", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId()).and().eq("trackId", AlbumRadioAudioPlayer.get().getPlayMusic().getTrackId()).queryForFirst();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if (resultQuery == null) {
                frameAnim = (AnimationDrawable) getResources().getDrawable(R.drawable.animator_download);
                imv_download.setImageDrawable(frameAnim);
                frameAnim.start();
            }
        }
    }

    @Override
    public void onChange(RecentAlbumRadioTrackBean album) {
        if (album == null) {
            imv_download.setImageResource(R.drawable.un_download);
            imv_favourite.setImageResource(R.drawable.favourite);
            imv_cover_art.setImageResource(R.drawable.default_cover);
            imv_vip_status.setImageResource(R.drawable.unvip);
            tv_mianing_time.setText("00:00");
            imv_cover_art.setImageResource(R.drawable.default_cover);
            return;
        }


        recent = album;
        mLastProgress = 0;
        localPercent = 0;


        pressMilliSeconds = 0;
        delay = 0;
        duration = 0;


        sb_progress.setMax(AlbumRadioAudioPlayer.get().getPlayMusic().getDuration());
        tv_album_name.setVisibility(View.VISIBLE);
        tv_album_name.setText(album.getAlbumName());
        if (action != null && action.isAccountRight()) {
            tv_program_name.setText(album.getTrackName());
        } else if (action != null && !action.isAccountRight()) {
            tv_program_name.setText(action.getTips());
        } else {
            tv_program_name.setText(album.getTrackName());
        }
        if (sb_progress != null) {
            sb_progress.setSecondaryProgress(0);
        }
        if (isAdded()) {
            Glide.with(this)
                    .load(album.getCover())
                    .into(imv_cover_art);
        }
        favStatus();
        if ("radio".equals(album.getType())) {
//            imv_play_status.setEnabled(true);
            imv_download.setEnabled(true);
            imv_favourite.setVisibility(View.VISIBLE);
            sb_progress.setVisibility(View.INVISIBLE);
            tv_mianing_time.setVisibility(View.INVISIBLE);
            imv_download.setVisibility(View.INVISIBLE);
            imv_download.setImageResource(R.drawable.cannotdownload);
            if (!album.isLive()) {
                sb_progress.setVisibility(View.VISIBLE);
                tv_mianing_time.setVisibility(View.VISIBLE);
            } else {
                sb_progress.setVisibility(View.VISIBLE);
                tv_mianing_time.setVisibility(View.INVISIBLE);
            }
            if (!album.isLive()) {
                sb_progress.setProgress(0);

                String str3 = "<font color='#f0f2f7'>" + formatTime("mm:ss", 0) + "</font><font color='#b3b6be'>" + "/" + formatTime("mm:ss", album.getDuration()) + "</font>";
                tv_mianing_time.setText(Html.fromHtml(str3));

//                tv_mianing_time.setText(formatTime("mm:ss", 0) + "/" + formatTime("mm:ss", album.getDuration()));
            }
//            imv_play_next.setOnLongClickListener(null);
        } else {


            if (downloadManager == null) {
                downloadManager = DownloadManager.getInstance(MusicApplication.GetInstance());
            }
            if (helper == null) {
                helper = DatabaseHelperOrm.getHelper(MusicApplication.GetInstance());
            }
            if (TextUtils.isEmpty(album.getDownloadUrl())) {
                imv_download.setImageResource(R.drawable.cannotdownload);
            } else {
                DownloadInfo downloadInfo = downloadManager.getTaskByUrl(album.getDownloadUrl());
                if (downloadInfo == null) {
                    imv_download.setImageResource(R.drawable.un_download);
                } else if (downloadInfo.getState() == DownloadManager.NONE) {
                    imv_download.setImageResource(R.drawable.un_download);
                } else if (downloadInfo.getState() == DownloadManager.WAITING) {
                    imv_download.setImageResource(R.drawable.un_download);
                } else if (downloadInfo.getState() == DownloadManager.FINISH) {
                    imv_download.setImageResource(R.drawable.downloadeded);
                } else if (downloadInfo.getState() == DownloadManager.ERROR) {
                    imv_download.setImageResource(R.drawable.un_download);
                    downloadManager.removeTaskByTrackId(album.getTrackId() + "");
                } else if (downloadInfo.getState() == DownloadManager.DOWNLOADING) {
                    frameAnim = (AnimationDrawable) getResources().getDrawable(R.drawable.animator_download);
                    imv_download.setImageDrawable(frameAnim);
                    frameAnim.start();
                }
            }


            imv_favourite.setVisibility(View.VISIBLE);
            sb_progress.setVisibility(View.VISIBLE);
            tv_mianing_time.setVisibility(View.VISIBLE);
            imv_download.setVisibility(View.VISIBLE);


            try {
                DownloadTrackDbBean result = helper.getDownloadDao().queryBuilder().where().eq("albumId", album.getAlbumId()).and().eq("userId", MusicApplication.GetUserId()).and().eq("trackId", album.getTrackId()).queryForFirst();
                if (result != null) {
                    imv_download.setImageResource(R.drawable.downloadeded);
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }


//            tv_mianing_time.setText(formatTime("mm:ss", 0) + "/" + formatTime("mm:ss", album.getDuration()));


            String str3 = "<font color='#f0f2f7'>" + formatTime("mm:ss", 0) + "</font><font color='#b3b6be'>" + "/" + formatTime("mm:ss", album.getDuration()) + "</font>";
            tv_mianing_time.setText(Html.fromHtml(str3));

            sb_progress.setProgress(0);
        }
    }

    @Override
    public void onPlayerStart() {
//        imv_play_status.setImageResource(R.drawable.to_pause);
        imv_play_status.setBackgroundResource(R.drawable.bg_status_pause);
        if (Constants.isRelease) {
            ConnectivityManager connectivityManager = (ConnectivityManager) MusicApplication.GetInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
            boolean connected = connectivityManager.getNetworkStatus();
            Logger.i("player start play-->" + connected);
            if (!connected) {
                if (ProcessInfoUtils.isForeground(MusicApplication.GetInstance())) {
//                    ToastUtils.show(getResources().getString(R.string.string_87));
                }
            }
        }
    }

    @Override
    public void onPlayerPause() {
//        imv_play_status.setImageResource(R.drawable.to_play);
        imv_play_status.setBackgroundResource(R.drawable.bg_status_play);
    }

    @Override
    public void onPublish(int progress, RecentAlbumRadioTrackBean radio) {
        if (sb_progress != null) {
            if (!isDraggingProgress) {
//                if ("album".equals(radio.getType())) {
//                    sb_progress.setProgress(progress);
//                    tv_mianing_time.setText(formatTime("mm:ss", progress) + "/" + formatTime("mm:ss", radio.getDuration()));
//                } else {
//                    sb_progress.setProgress(progress);
//                    tv_mianing_time.setText(formatTime("mm:ss", progress) + "/" + formatTime("mm:ss", radio.getDuration()));
//                }


                if (radio == null) {
                    sb_progress.setProgress(0);
                    return;
                }
                if ("album".equals(radio.getType())) {
                    duration = progress;
                    sb_progress.setProgress(progress);
//                    Logger.i("onPublish-->" + progress);

                    String str3 = "<font color='#f0f2f7'>" + formatTime("mm:ss", progress) + "</font><font color='#b3b6be'>" + "/" + formatTime("mm:ss", radio.getDuration()) + "</font>";
                    tv_mianing_time.setText(Html.fromHtml(str3));


//                    tv_mianing_time.setText(formatTime("mm:ss", progress) + "/" + formatTime("mm:ss", radio.getDuration()));
                } else {
                    if (radio.isLive()) {

//                        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
//                        try {
//                            Date startDate = sdf.parse(radio.getStartTime());
//                            Date nowDate=new Date();
//                            sb_progress.setProgress((int)(nowDate.getTime()-startDate.getTime()));
//                            tv_mianing_time.setText(formatTime("mm:ss", progress) + "/" + formatTime("mm:ss", radio.getDuration()));
//                        } catch (ParseException e) {
//                            e.printStackTrace();
//                        }
                        duration = 0;
                        sb_progress.setVisibility(View.VISIBLE);
                        tv_mianing_time.setVisibility(View.INVISIBLE);
                    } else {
//                        Logger.i("radio progress-->" + progress);
//                        Logger.i("radio duration-->" + radio.getDuration());
                        tv_mianing_time.setVisibility(View.VISIBLE);
                        duration = progress;
                        sb_progress.setProgress(progress);
//                        tv_mianing_time.setText(formatTime("mm:ss", progress) + "/" + formatTime("mm:ss", radio.getDuration()));


                        String str3 = "<font color='#f0f2f7'>" + formatTime("mm:ss", progress) + "</font><font color='#b3b6be'>" + "/" + formatTime("mm:ss", radio.getDuration()) + "</font>";
                        tv_mianing_time.setText(Html.fromHtml(str3));
                    }
                }
            }
        }
    }

    @Override
    public void onBufferingUpdate(int percent) {
//        Logger.i("percent-->" + percent);
        if (sb_progress != null) {
//            if (localPercent <= percent) {
            sb_progress.setSecondaryProgress(sb_progress.getMax() * percent / 100);
            localPercent = percent;
//            }
        }
    }

    @Override
    public void onPlayAlbumFinished(RecentAlbumRadioTrackBean radio) {
        recent = radio;
//        AlbumRadioAudioPlayer.get().seekTo(0);//为了实现下一节目的假操作
//        AlbumRadioAudioPlayer.get().pausePlayer();
//        ToastUtils.show("专辑播放结束了呀");
//        imv_play_status.setBackgroundResource(R.drawable.bg_imv_play);
    }

    @Override
    public void onFinishTrack() {
        if (sb_progress != null) {
//            sb_progress.setProgress(AlbumRadioAudioPlayer.get().getPlayMusic().getDuration());
//            AlbumRadioAudioPlayer.get().pausePlayer();
        }
    }

    @Override
    public void onToPrevAlbum(RecentAlbumRadioTrackBean source) {

    }

    @Override
    public void onToPayAlumTrack(RecentAlbumRadioTrackBean source) {
//        ToastUtils.show("此专辑为付费专辑 暂时不支持购买");
//        MaterialDialog dialog = new MaterialDialog.Builder(getContext()).title("提示").content("此专辑是付费专辑 暂不支持购买").positiveText("确定").negativeText("取消").onPositive(new MaterialDialog.SingleButtonCallback() {
//            @Override
//            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//            }
//        }).build();
//        dialog.show();
    }

    @Override
    public void onGetPlayInfo(long trackId) {

        radioModel.GetPlayInfo(trackId).subscribe(new CommonSubscriber<PlayInfoBean>() {
            @Override
            public void onSuccess(PlayInfoBean response) {
                if (response.getData() != null && !TextUtils.isEmpty(response.getData().getPlayUrl24Aac())) {
                    AlbumRadioAudioPlayer.get().setPlayUrl(response.getData().getPlayUrl24Aac());
                } else {
                    ToastUtils.show(R.string.string_80);
                }
            }

            @Override
            public void onFailure(BaseBean response) {
                ToastUtils.show(response.getStatusMessage());
            }
        });
    }

    @Override
    public void onGetPayDialog(long albumId, long trackId) {
//        radioModel.GetPriceInfo(albumId).subscribe(new CommonSubscriber<PriceTypeInfoBean>() {
//            @Override
//            public void onSuccess(PriceTypeInfoBean response) {
//                //以声音为单位进行购买
//                if (response.getData().getPriceTypeDetail().get(0).getPriceType() == 1) {
//                    if (dialog != null && dialog.isShowing()) {
//                        dialog.dismiss();
//                    }
//                    dialog = new MaterialDialog.Builder(getActivity()).title(getResources().getString(R.string.string_30)).content(getResources().getString(R.string.string_85)).positiveText(getResources().getString(R.string.string_32)).negativeText(getResources().getString(R.string.string_33)).onPositive(new MaterialDialog.SingleButtonCallback() {
//                        @Override
//                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                            placeOrder(false, response, trackId, trackId);
//                        }
//                    }).build();
//                    if (MusicApplication.GetInstance().getActivityNum() > 1) {
//                        Intent intent = new Intent(getActivity(), MainActivity.class);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                        startActivity(intent);
//                    }
//                    dialog.show();
//                }
//                //以专辑为单位进行购买
//                else {
////                    placeOrder(true, response, albumId);
//                    if (dialog != null && dialog.isShowing()) {
//                        dialog.dismiss();
//                    }
//                    dialog = new MaterialDialog.Builder(getActivity()).title(getResources().getString(R.string.string_30)).content(getResources().getString(R.string.string_86)).positiveText(getResources().getString(R.string.string_32)).negativeText(getResources().getString(R.string.string_33)).onPositive(new MaterialDialog.SingleButtonCallback() {
//                        @Override
//                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                            placeOrder(true, response, albumId, trackId);
//                        }
//                    }).build();
//                    if (MusicApplication.GetInstance().getActivityNum() > 1) {
//                        Intent intent = new Intent(getActivity(), MainActivity.class);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                        startActivity(intent);
//                    }
//                    dialog.show();
//                }
//            }
//
//            @Override
//            public void onFailure(BaseBean response) {
//
//            }
//        });
    }

    @Override
    public void onGetVIPDialog() {

    }


    private void placeOrder(boolean isBoughtByAlbum, PriceTypeInfoBean priceTypeInfo, long Id, long trackId) {
        PlaceOrderBean order = new PlaceOrderBean();
        order.setPriceType(priceTypeInfo.getData().getPriceTypeDetail().get(0).getPriceType());
        order.setPrice(priceTypeInfo.getData().getPriceTypeDetail().get(0).getDiscountedPrice() + "");
        order.setPayContent(Id);

        String vin = "";
        if (!TextUtils.isEmpty(PreferenceUtils.GetVinNum())) {
            Logger.i("vin-->" + PreferenceUtils.GetVinNum());
            vin = PreferenceUtils.GetVinNum();
        } else {
            File configFile = new File("/mnt/nfs/onlineapplication.conf");
            if (configFile.exists()) {
                String vinConfig = ConfigReaderUtils.readVidFromConfig();
                Logger.i("vinConfig-->" + vinConfig);
                vin = vinConfig;
            }
        }

        if (TextUtils.isEmpty(vin)) {
            vin = "LGVIN001000000001";
        }


        order.setVin(vin);


        Logger.i("vinCode-->" + vin);

        HttpClient.PlaceOrder(new Gson().toJson(order), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                ToastUtils.show("success");
                XiMaLaYaOrderBean result = new Gson().fromJson(response, XiMaLaYaOrderBean.class);
                Logger.i("PlaceOrder response-->" + response);
                if (result.getCode() == 0) {
                    Logger.i("OrderNo-->" + result.getData().getOrderNo());
                    PaySdk.getInstance().pay(getContext(), result.getData().getOrderNo() + "", order.getPrice(), "101", new NewPayResultListener() {
                        @Override
                        public void onPaySuccess(String s) {
                            ToastUtils.show("success");
                            Logger.i("");
                            if (isBoughtByAlbum) {
                                List<Track> tracks = new ArrayList<>();
                                tracks.addAll(AlbumRadioAudioPlayer.get().getTracks());
                                int index = 0;
                                for (Track track : tracks) {
                                    track.setIs_paid(true);
                                    track.setIs_authorized(true);
                                }
                                for (int position = 0; position < tracks.size(); position++) {
                                    if (trackId == tracks.get(position).getId()) {
                                        index = position;
                                    }
                                }
                                AlbumRadioAudioPlayer.get().setOnSources(tracks, index, 4, 0);
                            } else {
                                List<Track> tracks = new ArrayList<>();
                                tracks.addAll(AlbumRadioAudioPlayer.get().getTracks());
                                int index = 0;
                                for (int position = 0; position < tracks.size(); position++) {
                                    if (trackId == tracks.get(position).getId()) {
                                        index = position;
                                        tracks.get(position).setIs_paid(true);
                                        tracks.get(position).setIs_authorized(true);
                                    }
                                }
                                AlbumRadioAudioPlayer.get().setOnSources(tracks, index, 4, 0);
                            }
                        }

                        @Override
                        public void onPayFailed(String s) {

                        }
                    });
                } else {
                    ToastUtils.show(result.getStatusMessage());
                }
            }
        });
    }


    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (sb_progress != null) {
//            if(action!=null&&action.isAccountRight()){
            if (seekBar == sb_progress) {
                if (Math.abs(progress - mLastProgress) >= DateUtils.SECOND_IN_MILLIS) {
//                    tv_mianing_time.setText(formatTime("mm:ss", progress) + "/" + formatTime("mm:ss", AlbumRadioAudioPlayer.get().getPlayMusic().getDuration()));


                    String str3 = "<font color='#f0f2f7'>" + formatTime("mm:ss", progress) + "</font><font color='#b3b6be'>" + "/" + formatTime("mm:ss", AlbumRadioAudioPlayer.get().getPlayMusic().getDuration()) + "</font>";
                    tv_mianing_time.setText(Html.fromHtml(str3));


                    mLastProgress = progress;
                }
            }
//            }
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        if (seekBar == sb_progress) {
            isDraggingProgress = true;

        }
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if (seekBar == sb_progress) {
//            if(action!=null&&action.isAccountRight()){
            if (AlbumRadioAudioPlayer.get().getPlayMusic() != null && "album".equals(AlbumRadioAudioPlayer.get().getPlayMusic().getType())) {
                isDraggingProgress = false;
                if (AlbumRadioAudioPlayer.get().isPlaying() || AlbumRadioAudioPlayer.get().isPausing()) {
                    int progress = seekBar.getProgress();
                    AlbumRadioAudioPlayer.get().seekTo(progress);
                } else {
                    seekBar.setProgress(0);
                }
            } else if (AlbumRadioAudioPlayer.get().getPlayMusic() != null && "radio".equals(AlbumRadioAudioPlayer.get().getPlayMusic().getType()) && !AlbumRadioAudioPlayer.get().getPlayMusic().isLive()) {
                isDraggingProgress = false;
                if (AlbumRadioAudioPlayer.get().isPlaying() || AlbumRadioAudioPlayer.get().isPausing()) {
                    int progress = seekBar.getProgress();
                    AlbumRadioAudioPlayer.get().seekTo(progress);
                } else {
                    seekBar.setProgress(0);
                }
            }
//            }
        }
    }

    public static String formatTime(String pattern, long milli) {
        int m = (int) (milli / DateUtils.MINUTE_IN_MILLIS);
        int s = (int) ((milli / DateUtils.SECOND_IN_MILLIS) % 60);
        String mm = String.format(Locale.getDefault(), "%02d", m);
        String ss = String.format(Locale.getDefault(), "%02d", s);
        return pattern.replace("mm", mm).replace("ss", ss);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initPlayerView(AlbumRadioAudioPlayer.get().getPlayMusic());
    }

    private void initPlayerView(RecentAlbumRadioTrackBean album) {
        if (album == null) {
            return;
        }
        tv_album_name.setText(album.getAlbumName());
        if (action != null && !action.isAccountRight()) {
            tv_program_name.setText(action.getTips());
        } else {
            if (!TextUtils.isEmpty(album.getTrackName())) {
                tv_program_name.setText(album.getTrackName());
            } else {
                tv_program_name.setText("");
            }
        }
        sb_progress.setMax(album.getDuration());
        Glide.with(this)
                .load(album.getCover())
                .into(imv_cover_art);
    }

    @Override
    public void onResume() {
        super.onResume();
        favStatus();
        getVipInfo();
        if (AlbumRadioAudioPlayer.get().getPlayMusic() != null) {
            initPlayerView(AlbumRadioAudioPlayer.get().getPlayMusic());
            favStatus();
            if ("radio".equals(AlbumRadioAudioPlayer.get().getPlayMusic().getType())) {
                imv_download.setVisibility(View.INVISIBLE);
            } else {
                if (downloadManager == null) {
                    downloadManager = DownloadManager.getInstance(MusicApplication.GetInstance());
                }
                DownloadInfo downloadInfo = downloadManager.getTaskByUrl(AlbumRadioAudioPlayer.get().getPlayMusic().getDownloadUrl());
                if (TextUtils.isEmpty(AlbumRadioAudioPlayer.get().getPlayMusic().getDownloadUrl())) {
                    imv_download.setImageResource(R.drawable.cannotdownload);
                } else {
                    if (downloadInfo == null) {
                        if (AlbumRadioAudioPlayer.get().getPlayMusic().getFrom() == 1) {
                            imv_download.setImageResource(R.drawable.downloadeded);
                        } else {
                            imv_download.setImageResource(R.drawable.un_download);
                        }
                    } else if (downloadInfo.getState() == DownloadManager.NONE) {
                        imv_download.setImageResource(R.drawable.un_download);
                    } else if (downloadInfo.getState() == DownloadManager.WAITING || downloadInfo.getState() == DownloadManager.DOWNLOADING) {
                        imv_download.setImageResource(R.drawable.un_download);
                    } else if (downloadInfo.getState() == DownloadManager.FINISH) {
                        imv_download.setImageResource(R.drawable.downloadeded);
                    } else if (downloadInfo.getState() == DownloadManager.ERROR) {
                        imv_download.setImageResource(R.drawable.un_download);
                        downloadManager.removeTaskByTrackId(AlbumRadioAudioPlayer.get().getPlayMusic().getTrackId() + "");
                    }
                }
            }
        }
    }


    public void onEvent(RefreshFavStatusAction action) {
        favStatus();
    }

    public void onEvent(OnlineRadioItemSelectedAction action) {
//        getLiveingProgramDetail(localRaiods.get(action.getPosition()).getId(), action.getPosition());
    }


    public void setStatus(ShowHideUnavailableAction action) {
    }

    private Handler delayHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

//代码保护
            if (tv_album_name == null || tv_program_name == null) {
                return;
            }
            boolean isError = false;
            if (msg.arg1 == 1) {
                isError = true;
            } else {
                isError = false;
            }
            String tips = (String) msg.obj;
            if (isError) {
                isAccountRight = false;
                tv_album_name.setText(tips);
                tv_program_name.setText(tips);
                tv_album_name.setVisibility(View.INVISIBLE);
                tv_program_name.setVisibility(View.VISIBLE);
                action.setAccountRight(!isError);
                action.setTips(tips);
                setSeekbarEnable(false);
                layout_more.setEnabled(false);
                imv_more.setEnabled(false);
                PreferenceUtils.SaveVIPStatus(false);
                imv_vip_status.setImageResource(R.drawable.unvip);
            } else {
                isAccountRight = true;
                imv_play_status.setEnabled(true);
                layout_play_status.setEnabled(true);
                layout_more.setEnabled(true);
                imv_more.setEnabled(true);
                if (AlbumRadioAudioPlayer.get().getPlayMusic() == null) {
                    if (isAdded()) {
                        tv_album_name.setText(getResources().getString(R.string.string_34));
                        tv_program_name.setText(getResources().getString(R.string.string_34));
                    }
                    tv_album_name.setVisibility(View.INVISIBLE);
                    tv_program_name.setVisibility(View.VISIBLE);
                } else {
                    tv_album_name.setText(AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumName());
                    tv_program_name.setText(AlbumRadioAudioPlayer.get().getPlayMusic().getTrackName());
                    tv_album_name.setVisibility(View.VISIBLE);
                    tv_program_name.setVisibility(View.VISIBLE);
                }
                setSeekbarEnable(true);
            }


        }
    };

    private MessageAction action;


    public void setGesture(boolean isNear) {
        if (isNear) {
            layout_previous.setBackgroundResource(R.drawable.detail_background);
            layout_play_status.setBackgroundResource(R.drawable.detail_background);
            layout_play_next.setBackgroundResource(R.drawable.detail_background);
            layout_more.setBackgroundResource(R.drawable.detail_background);
        }
        else{
            layout_previous.setBackground(null);
            layout_play_status.setBackground(null);
            layout_play_next.setBackground(null);
            layout_more.setBackground(null);
        }
    }


    public void setErrorStatus(boolean isError, String tips) {
        action = new MessageAction();
        action.setAccountRight(!isError);
        action.setTips(tips);
        Message message = Message.obtain();
        message.obj = tips;
        if (isError) {
            message.arg1 = 1;
        } else {
            message.arg1 = 0;
        }

        delayHandler.sendMessageDelayed(message, 2000);
    }

    public void setAtmosphere(boolean rgbOn, String color) {
        if (rgbOn) {
            if (TextUtils.isEmpty(color)) {
                if (sb_progress != null) {
                    LayerDrawable layerDrawable = (LayerDrawable) sb_progress.getProgressDrawable();
                    Drawable drawable = layerDrawable.getDrawable(2);
                    drawable.setColorFilter(Color.parseColor("#e6be00"), PorterDuff.Mode.SRC);
                    layerDrawable.setDrawableByLayerId(android.R.id.progress, drawable);
                    imv_covert.setColorFilter(Color.parseColor("#e6be00"));
                    imv_cover_middle.setColorFilter(Color.parseColor("#e6be00"));
                    imv_cover_small.setColorFilter(Color.parseColor("#e6be00"));
                }
            } else {
                LayerDrawable layerDrawable = (LayerDrawable) sb_progress.getProgressDrawable();
                Drawable drawable = layerDrawable.getDrawable(2);
                drawable.setColorFilter(Color.parseColor(color), PorterDuff.Mode.SRC);
                layerDrawable.setDrawableByLayerId(android.R.id.progress, drawable);
                imv_covert.setColorFilter(Color.parseColor(color));
                imv_cover_middle.setColorFilter(Color.parseColor(color));
                imv_cover_small.setColorFilter(Color.parseColor(color));
            }
        } else {
            LayerDrawable layerDrawable = (LayerDrawable) sb_progress.getProgressDrawable();
            Drawable drawable = layerDrawable.getDrawable(2);
            drawable.setColorFilter(Color.parseColor("#e6be00"), PorterDuff.Mode.SRC);
            layerDrawable.setDrawableByLayerId(android.R.id.progress, drawable);
            imv_covert.setColorFilter(Color.parseColor("#e6be00"));
            imv_cover_middle.setColorFilter(Color.parseColor("#e6be00"));
            imv_cover_small.setColorFilter(Color.parseColor("#e6be00"));
        }
    }

    public void onEvent(ShowHideUnavailableAction action) {
        Logger.i(new Gson().toJson(action));
        if (action.isHide()) {
            layout_player.setVisibility(View.INVISIBLE);
            layout_not_available.setVisibility(View.VISIBLE);
            tv_hint.setText(action.getHintString());
        } else {
            layout_player.setVisibility(View.VISIBLE);
            layout_not_available.setVisibility(View.GONE);
        }
    }

    public void setShowHideAvaliable(ShowHideUnavailableAction action) {
        Logger.i(new Gson().toJson(action));
        if (action.isHide()) {
            layout_player.setVisibility(View.INVISIBLE);
            layout_not_available.setVisibility(View.VISIBLE);
            tv_hint.setText(action.getHintString());
        } else {
            layout_player.setVisibility(View.VISIBLE);
            layout_not_available.setVisibility(View.GONE);
        }
    }

    private void favStatus() {
        if (AlbumRadioAudioPlayer.get().getPlayMusic() == null) {
            return;
        }
        if (!"album".equals(AlbumRadioAudioPlayer.get().getPlayMusic().getType())) {
            imv_favourite.setVisibility(View.VISIBLE);
            imv_favourite.setEnabled(true);
        }
        try {
            FavouriteAlbumDbBean data = DatabaseHelperOrm.getHelper(getContext()).getFavouriteDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("id", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId()).queryForFirst();
            if (data == null) {
                imv_favourite.setImageResource(R.drawable.favourite);
            } else {
                imv_favourite.setImageResource(R.drawable.favourited);
            }
            imv_favourite.setEnabled(true);
            imv_favourite.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (AlbumRadioAudioPlayer.get().getPlayMusic() == null) {
                        return;
                    }

                    if (action != null && action.isAccountRight()) {
                        if (data == null) {


                            try {
                                List<FavouriteAlbumDbBean> datas = DatabaseHelperOrm.getHelper(getContext()).getFavouriteDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).query();
                                if (datas != null && datas.size() >= 30) {
//                                    if(!exceedFavNumDialog.isShowing()){
////                                        exceedFavNumDialog.show();
////                                    }


                                    NotificationManager notificationManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
                                    Intent setAlertIntent = new Intent("com.jpcc.vw.AlbumDetailActivity");
                                    PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, setAlertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                                    Popup popup = new Popup(getResources().getString(R.string.string_30), getResources().getString(R.string.string_112));
                                    popup.setActionOne(getResources().getString(R.string.string_32), pendingIntent);
                                    popup.setActionCancel(getResources().getString(R.string.string_33), "cancel");
                                    notificationManager.addPopup(0x0009, popup);
                                    return;
                                }
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }


                            FavouriteAlbumDbBean result = new FavouriteAlbumDbBean();
                            result.setUserId(MusicApplication.GetUserId());


                            result.setId(AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId());
                            result.setName(AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumName());
                            result.setHostName(AlbumRadioAudioPlayer.get().getPlayMusic().getAuthor());
                            result.setCoverUrlLarge(AlbumRadioAudioPlayer.get().getPlayMusic().getCover());
                            result.setType(AlbumRadioAudioPlayer.get().getPlayMusic().getType());
                            result.setVipFree(AlbumRadioAudioPlayer.get().getPlayMusic().isVipFree());
                            result.setTimeStamp(new Date().getTime());
                            try {
                                DatabaseHelperOrm.getHelper(getContext()).getFavouriteDao().create(result);
                                imv_favourite.setImageResource(R.drawable.favourited);
                                favStatus();
                                ToastUtils.show(R.string.string_57);
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }
                            AddAlbumCollectionBean bean = new AddAlbumCollectionBean();
                            bean.setAlbums(new ArrayList<>());
                            List<AddAlbumCollectionEntity> entitys = new ArrayList<>();
                            AddAlbumCollectionEntity entity = new AddAlbumCollectionEntity();
                            entity.setId(AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId());
                            entity.setName(AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumName());
                            entity.setHostName(AlbumRadioAudioPlayer.get().getPlayMusic().getAuthor());
                            entity.setCoverUrlSmall(AlbumRadioAudioPlayer.get().getPlayMusic().getCover());
                            entity.setCoverUrlMiddle(AlbumRadioAudioPlayer.get().getPlayMusic().getCover());
                            entity.setCoverUrlLarge(AlbumRadioAudioPlayer.get().getPlayMusic().getCover());
                            entity.setContentAbstract("");
                            entity.setCpSource("喜马拉雅");
                            entity.setCategoryId(0L);
                            entity.setPaid(false);
                            entitys.add(entity);
                            bean.setAlbums(entitys);
                            Logger.i("AddUserFavourite-->" + (new Gson().toJson(entitys)));
//                        HttpClient.AddUserFavourite(new Gson().toJson(entitys), new StringCallback() {
//                            @Override
//                            public void onError(Call call, Exception e, int id) {
//                                Logger.i("AddUserFavourite-->" + e.toString());
//                            }
//
//                            @Override
//                            public void onResponse(String response, int id) {
//                                Logger.i("AddUserFavourite-->" + response.toString());
//                            }
//                        });
                            AlbumRadioAudioPlayer.get().setSourceFrom(0);
                        } else {
                            try {
                                DatabaseHelperOrm.getHelper(getContext()).getFavouriteDao().delete(data);
                                imv_favourite.setImageResource(R.drawable.favourite);
                                favStatus();
                                ToastUtils.show(R.string.string_58);
                                AlbumRadioAudioPlayer.get().setSourceFrom(4);
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }


                            AddCancelAlbumBean addFav = new AddCancelAlbumBean();
                            List<String> radios = new ArrayList<>();
                            radios.add(AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId() + "");
                            addFav.setAlbums(radios);
//                        HttpClient.CancelUserFavourite(new Gson().toJson(radios), new StringCallback() {
//                            @Override
//                            public void onError(Call call, Exception e, int id) {
//                                ToastUtils.show(e.toString());
//                                Logger.i(e.toString());
//                            }
//
//                            @Override
//                            public void onResponse(String response, int id) {
//                                BaseBean result = new Gson().fromJson(response, BaseBean.class);
//                                if (Constants.STATUS_SUCCESS_CODE != result.getCode()) {
//                                    ToastUtils.show(result.getStatusMessage());
//                                    Logger.i(result.getStatusMessage());
//                                }
//                            }
//                        });


                        }
                    }
                }
            });
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
